package com.woniuxy.factories;


import com.woniuxy.Person;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;



/**
 * @Author: zhc
 * @Todo: TODO
 * @DateTime: 01/17/0017 下午 2:07
 * @Component: 成都蜗牛学苑
 **/
public class BeanFactory2 {
    static Map<String, Person> map=new HashMap();
    //1.读取配置文件
    static Properties properties = new Properties();
    static {

        //2.获取一个InputStream
        InputStream resourceAsStream = BeanFactory2.class.getResourceAsStream("beans.properties");
        //3.读取配置文件
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    /**
     * @Todo: 传入对应的类名首字母小写的，即可获取该对象
     * ChangeLog : 1. 创建 (01/17/0017 下午 2:11 [马宇航]);
     * @param name
     * @return com.woniuxy.Person
     */
    public Person getBean(String name){
        
        //4. 获取配置文件中所有的key
        for (String key:properties.stringPropertyNames()){
            //遍历后的key，来获取对应的value，这个value就是个全限定类名
            String property = properties.getProperty(key);
            try {
                Person person = (Person) Class.forName(property).newInstance();
                map.put(key,person);
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return map.get(name);
    }

}
